<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import axios from 'axios'

const router = useRouter()
const posts = ref([])
const loading = ref(false)
const refreshing = ref(false)
const finished = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)

// 获取帖子数据
const fetchPosts = async () => {
  try {
    // 获取token
    const token = sessionStorage.getItem("token")

    const config: any = {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        typeId: 2// 健身教程模块ID
      }
    }

    // 如果有token，则添加到请求头
    if (token) {
      config.headers = {
        'token': token
      }
    }

    const response = await axios.get('/api/post/page', config)

    if (response.data.code === 200) {
      const newPosts = response.data.data.records.map((post: any) => {
        // 处理用户信息
        if (!post.users) {
          post.users = {
            userId: post.userId || 0,
            nickname: '匿名用户',
            avatar: '',
            gender: '未知',
            height: 0,
            targetWeight: 0
          }
        }
        // 确保点赞数和评论数存在
        post.likes = post.likes !== undefined ? post.likes : 0
        post.commentCount = post.commentCount !== undefined ? post.commentCount : 0
        post.userLiked = post.userLiked || false
        console.log('Post data:', post) // 添加日志以便调试
        return post
      })

      if (refreshing.value) {
        posts.value = newPosts
        refreshing.value = false
      } else {
        posts.value = [...posts.value, ...newPosts]
      }

      // 判断是否还有更多数据
      if (pageNum.value >= response.data.data.pages || response.data.data.records.length < pageSize.value) {
        finished.value = true
      }
    } else {
      showToast('获取数据失败')
    }
  } catch (error) {
    showToast('网络错误')
    console.error('Error fetching posts:', error)
  } finally {
    loading.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  finished.value = false
  pageNum.value = 1
  fetchPosts()
}

// 上拉加载更多
const onLoad = () => {
  if (!refreshing.value && !finished.value) {
    pageNum.value++
    fetchPosts()
  } else {
    loading.value = false
  }
}

// 格式化时间显示
const formatTime = (timeString: string) => {
  // 添加安全检查
  if (!timeString) return ''

  const date = new Date(timeString)
  // 检查日期是否有效
  if (isNaN(date.getTime())) return ''

  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / (1000 * 60))

  if (minutes < 1) {
    return '刚刚'
  } else if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (minutes < 24 * 60) {
    const hours = Math.floor(minutes / 60)
    return `${hours}小时前`
  } else {
    const days = Math.floor(minutes / (24 * 60))
    return `${days}天前`
  }
}

// 点赞功能
const handleLike = async (post: any) => {
  try {
    const token = sessionStorage.getItem("token")

    // 检查是否有token
    if (!token) {
      showToast('请先登录')
      return
    }

    const response = await axios.get('/api/post/likes', {
      params: {
        postId: post.postId
      },
      headers: {
        'token': token
      }
    })

    if (response.data.code === 200) {
      // 更新点赞状态和数量
      post.likes = response.data.data.likes
      post.userLiked = response.data.data.isLiked
      showToast(response.data.msg)
    } else {
      showToast(response.data.msg || '操作失败')
    }
  } catch (error) {
    showToast('网络错误')
    console.error('Error liking post:', error)
  }
}

// 跳转到评论页面
const goToComment = (postId: number) => {
  router.push({
    path: '/comment',
    query: { postId: postId.toString() }
  })
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  fetchPosts()
})
</script>

<template>
  <div class="clockin-container">
    <van-nav-bar
      title="每日打卡"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    />

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div v-for="post in posts" :key="post.postId" class="post-item">
          <div class="post-header">
            <van-image
              :src="post.users?.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'"
              round
              width="40"
              height="40"
              class="user-avatar"
            />
            <div class="user-info">
              <div class="user-name">{{ post.users?.nickname || '匿名用户' }}</div>
              <div class="user-meta">
                <span class="gender">{{ post.users?.gender || '未知' }}</span>
                <span class="height">{{ post.users?.height || 0 }}cm</span>
                <span class="weight">目标: {{ post.users?.targetWeight || 0 }}kg</span>
              </div>
            </div>
            <div class="post-time">{{ formatTime(post.postTime) }}</div>
          </div>

          <div class="post-content">
            {{ post.content || '' }}
          </div>

          <!-- 图片展示 -->
          <div v-if="post.images" class="post-images">
            <div
              v-for="(image, index) in (post.images || '').split(',')"
              :key="index"
              class="image-container"
            >
              <van-image
                :src="image"
                width="100%"
                height="150"
                fit="cover"
                radius="8"
              />
            </div>
          </div>

          <!-- 点赞和评论 -->
          <div class="post-actions">
            <div class="like-section" @click="handleLike(post)">
              <van-icon
                :name="post.userLiked ? 'like' : 'like-o'"
                :color="post.userLiked ? '#1989fa' : '#ccc'"
                size="18"
              />
              <span :class="{ liked: post.userLiked }">{{ post.likes }}</span>
            </div>
            <div class="comment-section" @click="goToComment(post.postId)">
              <van-icon
                name="comment-o"
                color="#ccc"
                size="18"
              />
              <span>{{ post.commentCount }}</span>
            </div>
          </div>
        </div>

        <!-- 调试信息 -->
        <div v-if="posts.length === 0" style="text-align: center; padding: 20px;">
          暂无打卡内容
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<style scoped>
.clockin-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.post-item {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.user-avatar {
  margin-right: 12px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.user-meta {
  display: flex;
  font-size: 12px;
  color: #999;
}

.user-meta span {
  margin-right: 10px;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.post-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  margin-bottom: 12px;
  white-space: pre-wrap;
}

.post-images {
  display: flex;
  overflow-x: auto;
  gap: 10px;
  padding: 5px 0;
  margin-bottom: 12px;
}

.image-container {
  flex: 0 0 auto;
  width: 150px;
}

.post-actions {
  display: flex;
  gap: 20px;
}

.like-section, .comment-section {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.like-section span, .comment-section span {
  margin-left: 5px;
  font-size: 14px;
  color: #999;
}

.like-section .liked {
  color: #1989fa;
}
</style>